<template>
  <div class="order-container">
    <el-card class="order-card">
      <div slot="header" class="card-header">
        <span>订单列表</span>
        <div class="header-operations">
          <el-date-picker
            v-model="queryParams.month"
            type="month"
            placeholder="选择月份"
            format="yyyy-MM"
            value-format="yyyy-MM"
            :picker-options="pickerOptions"
            class="month-picker">
          </el-date-picker>
          <el-input
            v-model="queryParams.keyword"
            placeholder="请输入订单号"
            class="search-input"
            clearable
            prefix-icon="el-icon-search"
          >
          </el-input>
          <el-select
            v-model="queryParams.status"
            placeholder="订单状态"
            clearable
            class="status-select"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </div>
      </div>
      
      <el-table
        :data="orderList"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="code" label="订单号" width="220"></el-table-column>
        <el-table-column prop="operatorName" label="操作员" width="120" align="center"></el-table-column>
        <el-table-column prop="price" label="金额" width="140" align="center">
          <template slot-scope="scope">
            ¥{{ scope.row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="totalNumber" label="商品总数" width="140" align="center"></el-table-column>
        <el-table-column prop="status" label="状态" width="140" align="center">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="200" align="center">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" @click="handleView(scope.row)">查看</el-button>
            <el-button 
              v-if="scope.row.status === 'pending' || scope.row.status === 'unpaid'"
              type="text" 
              @click="handlePay(scope.row)"
              style="color: #67c23a">
              支付
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="queryParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
    
    <!-- 订单详情对话框 -->
    <el-dialog
      title="订单详情"
      :visible.sync="detailDialogVisible"
      width="700px"
      center>
      <div v-loading="detailLoading">
        <el-table
          :data="orderDetails"
          style="width: 100%"
          border>
          <el-table-column prop="productName" label="商品名称" width="220"></el-table-column>
          <el-table-column prop="number" label="数量" width="120" align="center"></el-table-column>
          <el-table-column prop="unitPrice" label="单价" width="150" align="center">
            <template slot-scope="scope">
              ¥{{ scope.row.unitPrice.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="totalPrice" label="小计" width="150" align="center">
            <template slot-scope="scope">
              ¥{{ scope.row.totalPrice.toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getOrderList, getOrderDetail, solveOrder } from '@/api/orders'

export default {
  name: 'OrderList',
  data() {
    return {
      queryParams: {
        page: 1,
        pageSize: 10,
        status: '',
        keyword: '',
        month: '',
        sortField: 'createTime',
        sortOrder: 'desc'
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        }
      },
      statusOptions: [
        { value: 'pending', label: '待支付' },
        { value: 'completed', label: '已完成' },
        { value: 'canceled', label: '已取消' }
      ],
      loading: false,
      total: 0,
      orderList: [],
      detailDialogVisible: false,
      detailLoading: false,
      orderDetails: []
    }
  },
  methods: {
    getStatusType(status) {
      const statusMap = {
        'paid': 'warning',      // 橙色
        'unpaid': 'primary',    // 蓝色
        'cancelled': 'info',    // 灰色
        'completed': 'warning', // 橙色
        'pending': 'primary',   // 蓝色
        'canceled': 'info'      // 灰色
      }
      return statusMap[status] || 'info'
    },
    getStatusText(status) {
      const statusMap = {
        'paid': '已付款',
        'unpaid': '待付款',
        'cancelled': '已取消',
        'completed': '已完成',
        'pending': '待支付',
        'canceled': '已取消'
      }
      return statusMap[status] || status
    },
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    handleSearch() {
      this.queryParams.page = 1;
      this.fetchData();
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.queryParams.page = val;
      this.fetchData();
    },
    handleView(row) {
      this.detailDialogVisible = true;
      this.detailLoading = true;
      this.orderDetails = [];
      
      // 发送请求获取订单详情
      getOrderDetail(row.id)
        .then(response => {
          if (response.code === 200 && response.data) {
            this.orderDetails = response.data;
            console.log('订单详情:', this.orderDetails);
          }
          // 错误会由全局拦截器处理
        })
        .catch(error => {
          console.error('获取订单详情失败:', error);
          // 错误会由全局拦截器处理
        })
        .finally(() => {
          this.detailLoading = false;
        });
    },
    handlePay(row) {
      this.$confirm('确认支付该订单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        solveOrder(row)
          .then(response => {
            if (response.code === 200) {
              this.$message.success('支付成功');
              // 检查当前路由，如果是库存状态页面则刷新
              if (this.$route.path === '/inventory/stock') {
                this.$router.go(0);
              }
            }
            // 错误会由全局拦截器处理
          })
          .catch(error => {
            console.error('支付失败:', error);
            // 错误会由全局拦截器处理
          });
      }).catch(() => {
        this.$message.info('已取消支付');
      });
    },
    fetchData() {
      this.loading = true;
      
      // 调用API获取订单列表
      getOrderList(this.queryParams)
        .then(response => {
          if (response.code === 200 && response.data) {
            this.orderList = response.data.records || [];
            this.total = response.data.total || 0;
          } else {
            // 错误会由全局拦截器处理
            this.orderList = [];
            this.total = 0;
          }
        })
        .catch(error => {
          console.error('获取订单列表失败:', error);
          // 错误会由全局拦截器处理
          this.orderList = [];
          this.total = 0;
        })
        .finally(() => {
          this.loading = false;
        });
    }
  },
  mounted() {
    this.fetchData();
    
    // 添加事件监听，用于结算完成后刷新订单列表
    this.$root.$on('checkout-completed', this.fetchData);
  },
  
  beforeDestroy() {
    // 移除事件监听以防止内存泄漏
    this.$root.$off('checkout-completed', this.fetchData);
  }
}
</script>

<style scoped>
.order-container {
  padding: 20px;
  background: #f0f2f5;
  min-height: calc(100vh - 120px);
}

.order-card {
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #304156;
}

.header-operations {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 200px;
}

.status-select {
  width: 120px;
}

.month-picker {
  width: 130px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* Element UI 主题覆盖 */
:deep(.el-button--primary) {
  background-color: #ff6b00;
  border-color: #ff6b00;
}

:deep(.el-button--primary:hover),
:deep(.el-button--primary:focus) {
  background-color: #ff8533;
  border-color: #ff8533;
}

:deep(.el-button--text) {
  color: #ff6b00;
}

:deep(.el-button--text:hover),
:deep(.el-button--text:focus) {
  color: #ff8533;
}

/* 标签样式 */
:deep(.el-tag--success) {
  background-color: rgba(103, 194, 58, 0.1);
  border-color: rgba(103, 194, 58, 0.2);
  color: #67c23a;
}

:deep(.el-tag--primary) {
  background-color: rgba(64, 158, 255, 0.1);
  border-color: rgba(64, 158, 255, 0.2);
  color: #409eff;
}

:deep(.el-tag--warning) {
  background-color: rgba(230, 162, 60, 0.1);
  border-color: rgba(230, 162, 60, 0.2);
  color: #e6a23c;
}

:deep(.el-tag--danger) {
  background-color: rgba(245, 108, 108, 0.1);
  border-color: rgba(245, 108, 108, 0.2);
  color: #f56c6c;
}

/* 输入框 */
:deep(.el-input__inner:focus) {
  border-color: #ff6b00;
}

:deep(.el-input__prefix) {
  color: #909399;
}

:deep(.el-input.is-active .el-input__inner) {
  border-color: #ff6b00;
}

/* 下拉框 */
:deep(.el-select-dropdown__item.selected) {
  color: #ff6b00;
}

:deep(.el-select .el-input.is-focus .el-input__inner) {
  border-color: #ff6b00;
}

:deep(.el-select .el-input__inner:focus) {
  border-color: #ff6b00;
}

:deep(.el-select-dropdown__item.hover, .el-select-dropdown__item:hover) {
  background-color: rgba(255, 107, 0, 0.1);
}

/* 日期选择器 */
:deep(.el-date-picker__header-label.active),
:deep(.el-date-picker__header-label:hover) {
  color: #ff6b00;
}

:deep(.el-date-table td.current:not(.disabled)) {
  color: #fff;
  background-color: #ff6b00;
}

:deep(.el-date-table td.today:not(.disabled)) {
  color: #ff6b00;
}

:deep(.el-date-table td.available:hover) {
  color: #ff6b00;
}

:deep(.el-picker-panel__icon-btn:hover) {
  color: #ff6b00;
}

:deep(.el-date-picker .el-time-panel__btn.confirm) {
  color: #ff6b00;
}

:deep(.el-month-table td.current:not(.disabled) .cell) {
  color: #fff;
  background-color: #ff6b00;
}

:deep(.el-month-table td .cell:hover) {
  color: #ff6b00;
  background-color: rgba(255, 107, 0, 0.1);
}

:deep(.el-year-table td.current:not(.disabled) .cell) {
  color: #fff;
  background-color: #ff6b00;
}

:deep(.el-year-table td .cell:hover) {
  color: #ff6b00;
  background-color: rgba(255, 107, 0, 0.1);
}

.el-card {
  border-radius: 8px;
}

.el-card__header {
  padding: 15px 20px;
  border-bottom: 1px solid #e6e6e6;
}

.el-table {
  color: #304156;
}

.el-table th {
  background-color: #f5f7fa;
  color: #304156;
}

:deep(.el-pagination.is-background .el-pager li:not(.disabled).active) {
  background-color: #ff6b00;
}

:deep(.el-pagination.is-background .el-pager li:not(.disabled):hover) {
  color: #ff6b00;
}

/* 订单详情样式 */
.el-dialog__body {
  padding: 20px;
}
</style> 